package com.yunjing.mvparmsdemo.mvp.ui.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.yunjing.mvparmsdemo.R;

import butterknife.BindView;

public class NewDetailsActivity extends BaseActivity {

    @BindView(R.id.webView)
    WebView mWebView;
    private String mWebUrl;
    private WebSettings mWebSettings;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {

    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_new_details;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (getIntent() != null) {
            mWebUrl = getIntent().getStringExtra("web_url");
        }
        initWebView();
    }

    private void initWebView() {
        mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        /**
         *  Webview在安卓5.0之前默认允许其加载混合网络协议内容
         *  在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebSettings.setSaveFormData(true); // 是否保存产生的数据
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAllowFileAccessFromFileURLs(false);
        mWebSettings.setAllowUniversalAccessFromFileURLs(false);
        mWebSettings.setJavaScriptEnabled(true); // 是否启用JAVA脚本
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setSupportZoom(false);
        mWebSettings.setBuiltInZoomControls(false); // 是否支持缩放
        mWebSettings.setDisplayZoomControls(false);

        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.requestFocusFromTouch();


        mWebView.setWebChromeClient(new WebChromeClient());//这行最好不要丢掉
        //该方法解决的问题是打开浏览器不调用系统浏览器，直接用webview打开
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView mView, String url) {
                mView.loadUrl(url);
                return true;
            }

            @JavascriptInterface
            @Override
            public void onPageStarted(WebView view, String u, Bitmap favicon) {
                super.onPageStarted(view, u, favicon);

            }

            @JavascriptInterface
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //拦截上海银行回调url
                //if (url.contains("returnurl/payreturn")) {
                //注入一段js代码
                String jsCode = "javascript: (function(){ " +
                        "var btn=document.getElementById('regist_n_submit');" +
                        "btn.onclick=function(){window.app.toMyFragment();} " +
                        "})()";
                view.loadUrl(jsCode);

            }

            @JavascriptInterface
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//              super.onReceivedSslError(view, handler, error);//注意这个存在重定向url super方法中存在 默认不安全导致空白页面
                handler.proceed();
//              handleMessage(Message msg); 其他处理
            }
        });
        if (!TextUtils.isEmpty(mWebUrl)) {
            mWebView.loadUrl(mWebUrl);
        }

    }

    // 解决html alert和conse打印不出来的问题
    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.e("test", cm.message() + " -- From line "
                    + cm.lineNumber() + " of "
                    + cm.sourceId());
            return true;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            ArmsUtils.makeText(NewDetailsActivity.this, message);
            result.confirm();
            //result.cancel();
            return false;
        }

    }
}
